package com.qmth.gkwb.web.view;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.security.auth.login.LoginException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qmth.gkwb.data.document.Settings;
import com.qmth.gkwb.data.document.TimeConfig;
import com.qmth.gkwb.data.entity.StudentUser;
import com.qmth.gkwb.data.repository.SettingRepo;
import com.qmth.gkwb.data.security.UserService;
import com.qmth.gkwb.data.system.SettingService;

@Controller
@RequestMapping("view/login")
public class LoginController {

	@Autowired private UserService userService;
	@Autowired private SettingService settingService;
	
	@RequestMapping
	@ResponseBody
	public StudentUser index(@RequestBody StudentUser user) throws LoginException{
		StudentUser su = userService.getStudentUserByUserId(user.getUserId());
		if(su == null){
			throw new LoginException("报名号或身份证号不存在！");
		}
		else{
			if(!user.getPassword().equals(su.getPassword())){
				throw new LoginException("密码错误！");
			}
			//判断报名时间设置
			Settings settings = settingService.getSettings();
			//判断系统是否开启
			boolean isSysEnabled = settings.isSystemEnabled();
			if(!isSysEnabled){
				throw new LoginException("系统已关闭！");
			}
			//判断报名时间段
			Date start = settings.getSystemStartTime();
			SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
			Date end = settings.getSystemEndTime();
			Date now = Calendar.getInstance().getTime();
			
			//判断非艺术类区域登录限制
			String cityNo = su.getUserId().substring(2,6);
			TimeConfig config = settingService.getCityTime(cityNo, settings);
			String type = su.getUserId().substring(8,10);
			if((type.equals("13") || type.equals("17")) && start != null && now.before(start)){
				throw new LoginException("不在报名时间内，艺术类考生报名开始时间为："+sdf.format(start));
			}
			if((type.equals("13") || type.equals("17")) && end != null && now.after(end)){
				throw new LoginException("不在报名时间内，艺术类考生报名结束时间为："+sdf.format(end));
			}
			if(config != null && !type.equals("13") && !type.equals("17") && (now.after(config.getEnd()) || now.before(config.getStart()))){
				throw new LoginException("不在报名时间内！\n"+config.getName()+"的报名时间为："+sdf.format(config.getStart())+"至"+sdf.format(config.getEnd()));
			}
		}
		return su;
	}
}
